import requests
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
import sys
from multiprocessing import Process


def start_browser(ads_id):
    open_url = f"http://local.adspower.com:50325/api/v1/browser/start?user_id={ads_id}"
    close_url = f"http://local.adspower.com:50325/api/v1/browser/stop?user_id={ads_id}"

    try:
        resp = requests.get(open_url).json()
        print(resp)
        if resp["code"] != 0:
            print(resp["msg"])
            print("please check ads_id")
            return

        chrome_driver = resp["data"]["webdriver"]
        service = Service(executable_path=chrome_driver)
        chrome_options = Options()
        chrome_options.add_experimental_option("debuggerAddress", resp["data"]["ws"]["selenium"])
        driver = webdriver.Chrome(service=service, options=chrome_options)

        print(driver.title)
        driver.get("https://www.baidu.com/")
        time.sleep(2)

        # test
        inputText = driver.find_element(By.CLASS_NAME, "s_ipt")
        inputText.send_keys("bitcoin")
        time.sleep(100)

    finally:
        resp = requests.get(close_url).json()
        print(f"Browser closed for {ads_id}, response: {resp}")


def main():
    ads_ids = ["jhkilmi", "jhkmexy"]  # 多个 IDs
    processes = []

    for ads_id in ads_ids:
        p = Process(target=start_browser, args=(ads_id,))
        p.start()
        processes.append(p)

    for p in processes:
        p.join()


if __name__ == "__main__":
    main()
